const express = require('express');
const fs = require('fs');
const path = require('path');

module.exports = function createVtTargetRouter(TARGET_DIR) {
    const router = express.Router();
    router.use('/files', express.static(TARGET_DIR));

    // 获取所有VT目标
    router.get('/', (req, res) => {
        const data = getAllTargetsInfo();
        res.json(data);
    });


    // 获取单个目标详细信息
    router.get('/:name', (req, res) => {
        const { name } = req.params;
        const { objlist } = getAllTargetsInfo();
        const target = objlist.find(item => item.obj_name === name);
        
        if (target) {
            res.json(target);
        } else {
            res.status(404).json({ error: 'Target not found' });
        }
    });


    // 提供图片文件
    router.get('/:name/image', (req, res) => {
    const targetName = req.params.name;
    const imagePath = path.join(TARGET_DIR, targetName, `${targetName}.png`);
    
    if (fs.existsSync(imagePath)) {
        res.sendFile(imagePath);
    } else {
        res.status(404).send('图片不存在');
    }
    });

    // 获取所有目标信息
    function getAllTargetsInfo() {

        const quickLookDir = path.join(TARGET_DIR, 'quickLook');
        const refinedDir = path.join(TARGET_DIR, 'refined');
        
        const objlist = [];
        const typeStats = {
            GRB: 0,
            'ToO-NOM-AT': 0,
            'ToO-NOM-GRB': 0,
            'ToO-NOM-ACAL': 0,
            'ToO-EX': 0,
            GP: 0,
            total: 0
        };

        // 获取所有类型
        const types = fs.readdirSync(quickLookDir).filter(f => 
            fs.statSync(path.join(quickLookDir, f)).isDirectory()
        );

        // 先收集所有目标的基本信息
        const targetMap = new Map();

        for (const type of types) {
            const typeDir = path.join(quickLookDir, type);
            const targets = fs.readdirSync(typeDir).filter(f => 
                fs.statSync(path.join(typeDir, f)).isDirectory()
            );

            for (const target of targets) {
                if (!targetMap.has(target)) {
                    targetMap.set(target, {
                        info: {},
                        obslist: [],
                        latestRefinedDate: null
                    });
                }

                const targetData = targetMap.get(target);
                const quickLookTargetDir = path.join(quickLookDir, type, target);
                const refinedTargetDir = path.join(refinedDir, type, target);

                // 读取当前类型的info文件
                const infoFile = path.join(quickLookTargetDir, `${target}.info`);
                const currentTypeInfo = {};
                if (fs.existsSync(infoFile)) {
                    const infoContent = fs.readFileSync(infoFile, 'utf-8');
                    infoContent.split('\n').forEach(line => {
                        const [key, value] = line.split('=').map(item => item.trim());
                        if (key && value) {
                            currentTypeInfo[key] = value;
                        }
                    });
                }

                // 收集quickLook文件
                const quickLook = {
                    lightCurveData: null,
                    lightCurveImage: null,
                    identifyImages: []
                };

                fs.readdirSync(quickLookTargetDir).forEach(file => {
                    if (file === `${target}.quicklook.txt`) {
                        quickLook.lightCurveData = path.join('quickLook', type, target, file);
                    } else if (file === `${target}.quicklook.png`) {
                        quickLook.lightCurveImage = path.join('quickLook', type, target, file);
                    } else if (file.startsWith('SVT') && file.endsWith('.png')) {
                        quickLook.identifyImages.push(path.join('quickLook', type, target, file));
                    }
                });

                // 收集refined文件
                const refined = {
                    lightCurveData: null,
                    lightCurveImage: null,
                    identifyImages: []
                };

                if (fs.existsSync(refinedTargetDir)) {
                    fs.readdirSync(refinedTargetDir).forEach(file => {
                        if (file === `${target}.refined.txt`) {
                            refined.lightCurveData = path.join('refined', type, target, file);
                        } else if (file === `${target}.refined.png`) {
                            refined.lightCurveImage = path.join('refined', type, target, file);
                        } else if (file.startsWith('SVT') && file.endsWith('.png')) {
                            refined.identifyImages.push(path.join('refined', type, target, file));
                        }
                    });
                }

                // 获取当前类型的refined_date
                const currentRefinedDate = currentTypeInfo.refined_date || null;
                
                // 更新最新refined_date
                if (currentRefinedDate) {
                    if (!targetData.latestRefinedDate || 
                        new Date(currentRefinedDate) > new Date(targetData.latestRefinedDate)) {
                        targetData.latestRefinedDate = currentRefinedDate;
                    }
                }

                // 合并基本信息（优先保留已存在的值）
                Object.keys(currentTypeInfo).forEach(key => {
                    if (!targetData.info[key]) {
                        targetData.info[key] = currentTypeInfo[key];
                    }
                });

                // 添加到obslist
                targetData.obslist.push({
                    type: type,
                    refined_date: currentRefinedDate,
                    quickLook: quickLook,
                    refined: refined
                });

                // 更新统计
                typeStats[type]++;
            }
        }

        // 转换为objlist，设置最新的refined_date
        targetMap.forEach((targetData, targetName) => {
            objlist.push({
                ...targetData.info,
                obj_name: targetName,
                refined_date: targetData.latestRefinedDate || targetData.info.refined_date || null,
                obslist: targetData.obslist
            });
            typeStats.total++;
        });

        // 按Trig_T0倒序排序
        objlist.sort((a, b) => {
            const dateA = new Date(a.Trig_T0 || 0);
            const dateB = new Date(b.Trig_T0 || 0);
            return dateB - dateA;
        });

        return { objlist, stats: typeStats };
    }
    return router;
};
